﻿using DataMonitor_IBLL;
using DataMonitor_Tools.Tools.SMTP;
using DataMonitorMysql.MappingClass;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System.Reflection;

namespace DataMonitorWebApi.Controllers
{
    [Route("[controller]/[action]")]
    [ApiController]
    public class SystemVersionController : ControllerBase
    {
        private readonly ILogger<SystemVersionController> _logger;
        private readonly IBLL_SystemVersion _bLL_SystemVersion;
        private readonly string controllerName;
        private readonly IMemoryCache _memoryCache;//内存缓存
        public SystemVersionController(ILogger<SystemVersionController> logger, IBLL_SystemVersion bLL_SystemVersion,  IMemoryCache memoryCache)
        {
            _logger = logger;
          
            controllerName = this.GetType().Name;
            _bLL_SystemVersion = bLL_SystemVersion;
            _memoryCache = memoryCache;

        }
        [HttpGet]
        public IActionResult GetSystemVersion(int page, int pagesize)
        {
            var data = _bLL_SystemVersion.LoadEntities(a => true);
            var datacount = data.Count();
            var pagedata = data.Skip((page - 1) * pagesize).Take(pagesize).OrderBy(a => a.key);
            return Ok(new { pagedata, total = datacount });
        }

        [HttpGet]
        public IActionResult GetLatestSystemVersion()
        {
            var version = _memoryCache.GetOrCreate<string>("latestversion", value =>
            {
                var data = _bLL_SystemVersion.LoadEntities(a => true).OrderBy(a=>a.key).LastOrDefault();
                if (data != null)
                {
                    return data.version;
                }
                else
                {
                    return "1.0.0";
                }
            });
            
            return Ok(version);
        }
        [HttpPost]
        public IActionResult AddSystemVersion([FromBody] dm_systemversion row)
        {
            //先按照key来排序获得最后一个数据
            var last = _bLL_SystemVersion.LoadEntities(a => true).OrderBy(a => a.key).LastOrDefault();
            if (last != null)
            {
                //把要添加的数据的key改为最后一个数据的key+1，这样数据库里就是连续的数据，不会出现断档的key
                row.key = last.key + 1;
            }
            else
            {
                row.key = 1;
            }
            //^[a-zA-Z0-9,_]*$   只出现","或者"_"，不需要开头和结尾都是英文逗号，其他符号不准出现，数字字母没限制
            var isaddsucess = _bLL_SystemVersion.AddEntity(row);
            var t = MethodBase.GetCurrentMethod();
            string? methodName = t?.Name;
            if (isaddsucess)
            {
                _memoryCache.Remove("latestversion");
                _logger.LogInformation($"{controllerName}控制器{methodName}方法,执行成功：{DateTime.Now}");
                return Ok("添加成功");
            }
            else
            {
                _logger.LogError($"{controllerName}控制器{methodName}方法,执行失败-数据库操作失败：{DateTime.Now}");

                return BadRequest("添加失败");
            }
        }
        [HttpPut]
        public IActionResult EditSystemVersion([FromBody] dm_systemversion row)
        {
            //row.updatetime = row.updatetime.AddDays(1);
            var t = MethodBase.GetCurrentMethod();
            string? methodName = t?.Name;
            var iseditsucess = _bLL_SystemVersion.EditEntity(row);
            if (iseditsucess)
            {
                _memoryCache.Remove("latestversion");
                _logger.LogInformation($"{controllerName}控制器{methodName}方法,执行成功：{DateTime.Now}");
                return Ok("编辑成功");
            }
            else
            {
                _logger.LogError($"{controllerName}控制器{methodName}方法,执行失败-数据库操作失败：{DateTime.Now}");

                return BadRequest("编辑失败");
            }
        }
        [HttpDelete]
        public IActionResult DelSystemVersion(int key)
        {
            var t = MethodBase.GetCurrentMethod();
            string? methodName = t?.Name;
            var data = _bLL_SystemVersion.LoadEntities(a => true).Where(a => a.key == key).FirstOrDefault();

            if (data != null)
            {
                var isdelsuccess = _bLL_SystemVersion.DeleteEntity(data);
                if (isdelsuccess)
                {
                    _memoryCache.Remove("latestversion");
                    _logger.LogInformation($"{controllerName}控制器{methodName}方法,参数为{key}执行成功：{DateTime.Now}");
                    return Ok("删除成功");
                }
                else
                {
                    _logger.LogError($"{controllerName}控制器{methodName}方法,参数为{key}执行失败：{DateTime.Now}");
                    return BadRequest("删除失败");
                }
            }
            else
            {
                _logger.LogInformation($"{controllerName}控制器{methodName}方法,参数为{key}执行失败-找不到数据：{DateTime.Now}");
                return BadRequest("数据库找不到数据");
            }

        }


    }
}
